package baiqi.sishen.community.controller;

import baiqi.sishen.community.dto.AccessTokenDto;
import baiqi.sishen.community.mapper.UserMapper;
import baiqi.sishen.community.model.User;
import baiqi.sishen.community.provider.GiteeProvider;
import baiqi.sishen.community.provider.model.GiteeUser;
import baiqi.sishen.community.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author 兕神
 * @version 1.0
 * DateTime: 2023/4/26
 */
@Controller
public class AuthorizeController {

    @Resource
    private GiteeProvider giteeProvider;

    @Value("${gitee.client.id}")
    private String clientId;

    @Value("${gitee.client.secret}")
    private String clientSecret;

    @Value("${gitee.redirect.uri}")
    private String redirectUri;

    @Resource
    private UserService userService;

    @GetMapping("/callback")
    public String callback(
            @RequestParam("code") String code,
            @RequestParam("state") String state,
            HttpServletResponse response) {
        AccessTokenDto accessTokenDto = new AccessTokenDto();
        accessTokenDto.setCode(code);
        accessTokenDto.setState(state);
        accessTokenDto.setClient_secret(clientSecret);
        accessTokenDto.setClient_id(clientId);
        accessTokenDto.setRedirect_uri(redirectUri);

        String accessToken = giteeProvider.accessToken(accessTokenDto);
        GiteeUser giteeUser = giteeProvider.getGiteeUser(accessToken);
        //若用户不为空，则保存用户信息到数据库
        if (giteeUser != null && giteeUser.getId() != null) {
            User user = new User();
            user.setAccountId(giteeUser.getId().toString());
            user.setAvatarUrl(giteeUser.getAvatarUrl());
            user.setBio(giteeUser.getBio());
            user.setName(giteeUser.getName());
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            userService.insertOrUpdate(user);
            //返回token给服务器，作为登录凭证
            response.addCookie(new Cookie("token",token));
        }
        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout(
            HttpServletRequest request,
            HttpServletResponse response){
        request.getSession().removeAttribute("user");

        Cookie cookie = new Cookie("token","");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
